package pet_pavilion.yushougeums.security;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import pet_pavilion.yushougeums.mapper.UserMapper;
import pet_pavilion.yushougeums.pojo.vo.UserLoginInfoVO;

import java.util.ArrayList;
import java.util.List;

/**
 * Spring Security处理认证时使用到的获取管理员登录详情的实现类
 *
 * @author java@tedu.cn
 * @version 0.0.1
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.warn("Spring Security框架自动调用了UserDetailsServiceImpl.loadUserByUsername()方法，用户名：{}", username);
        System.out.println(username);
        // 根据用户名从数据库中查询匹配的用户信息
        UserLoginInfoVO loginInfo = userMapper.getLoginInfoByUsername(username);
        log.warn("从数据库中根据用户名【{}】查询登录信息，结果：{}", username, loginInfo);

        if (loginInfo == null) {
            log.warn("此用户名没有匹配的用户数据，将返回null");
            return null;
        }

        log.warn("用户名匹配成功！准备返回此用户名匹配的UserDetails类型的对象");
        List<GrantedAuthority> authorities = new ArrayList<>();
        List<String> permissions = loginInfo.getPermissions();
        for (String permission : permissions) {
            authorities.add(new SimpleGrantedAuthority(permission));
        }
        log.info("{},{}",authorities,permissions);


        pet_pavilion.yushougeums.security.UserDetails userDetails = new pet_pavilion.yushougeums.security.UserDetails(
                loginInfo.getId(),
                loginInfo.getUsername(),
                loginInfo.getPassword(),
                loginInfo.getEnable() == 1,
                authorities) {
        };
        log.warn("即将向Spring Security返回UserDetails类型的对象：{}", userDetails);
        System.out.println("********************************"+userDetails);
        return userDetails;
    }

}
